<template>
	<div class="stay-school-record">
		<nav-header></nav-header>

        <div class="zh-table">
            <div class="zh-table-open clear">
				<div class="zh-open-left fl">
					<div class="open-width" style="width: 250px">
                        <el-date-picker
                            v-model="listParam.pickerTime"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                            range-separator=" - "
                            start-placeholder="开始留校日期"
                            end-placeholder="结束留校日期">
                        </el-date-picker>
					</div>
                    <div class="open-width" style="width: 130px">
                        <el-select v-model="listParam.dormId" filterable placeholder="请选择宿舍楼">
                            <el-option
                                v-for="item in dormData"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="open-width" style="width: 160px">
                        <el-cascader
                            placeholder="请选择班级"
                            :options="gradeList"
                            @change="changeAddItem"
                            style="width: 100%"
                            v-model="listParam.classId">
                        </el-cascader>
                    </div>
					<div class="open-width" style="width: 175px">
						<el-input v-model="listParam.keyword" placeholder="输入账号、姓名、寝室号" @keyup.enter.native="searchFunc"></el-input>
					</div>
					<el-button type="primary" @click="searchFunc">搜索</el-button>
					<el-button type="primary" @click="resetList">重置</el-button>
				</div>
				<div class="zh-open-right fr">
                    <el-button type="primary" @click="newStaySchool('add')">添加留校</el-button>
                    <el-button type="primary" @click="batchImport">批量导入</el-button>
                    <el-button type="primary" @click="getAllData">批量导出</el-button>
					<el-button type="danger" @click="deleteAllConfirm">批量删除</el-button>
				</div>
			</div>

            <div class="zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt">
                <el-table
                    :data="listData"
                    fixed
                    border
                    max-height="600"
                    @selection-change="tableSelectionChange"
                    style="width: 100%">
                    <el-table-column
                        type="selection"
                        width="50"
                        align="center"
                        fixed>
                    </el-table-column>
                    <el-table-column
                        type="index"
                        :index="tableIndex"
                        label="序号"
                        align="center"
                        show-overflow-tooltip
                        width="50">
                    </el-table-column>
                    <el-table-column
                        prop="start_time"
                        label="开始时间"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="end_time"
                        label="结束时间"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="user_number"
                        label="账号"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="user_name"
                        label="真实姓名"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="org_name"
                        label="班级"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="building_name"
                        label="留校宿舍楼"
                        align="center"
                        width="100px"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="dormitory_name"
                        label="留校寝室"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="bed_number"
                        label="床位"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="housemaster_name"
                        label="宿管老师"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="housemaster_telphone"
                        label="联系电话"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop=""
                        label="留校说明"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            {{scope.row.content ? scope.row.content : '-'}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        :width="120">
                        <template slot-scope="scope">
                            <el-button @click="newStaySchool(scope.row)" type="text">编辑</el-button>
                            <el-button @click="deleteConfirm(scope.row.id)" type="text" class="delete-button">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="table-pagination" v-show="totalNumber > 10">
                    <el-pagination
                        @size-change="setCurrentSize"
                        @current-change="setCurrentPage"
                        :current-page="listParam.pageIndex"
                        :page-sizes="[10, 20, 30, 40, 50, 100]"
                        :page-size="listParam.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalNumber">
                    </el-pagination>
                </div>
            </div>
        </div>

        <el-dialog 
            class="stay-add" 
            :title="stayTitle" 
            :visible.sync="stayVisible" 
            :before-close="cancelForm"
            :close-on-click-modal="false" 
            :close-on-press-escape="false" 
            width="500px">
			<el-form :model="stayForm" :rules="rules" ref="stayForm" label-width="100px" class="stay-form">
                <el-form-item label="开始时间：" prop="pickerDateS">
                    <el-date-picker
                        v-model="stayForm.pickerDateS"
                        value-format="yyyy-MM-dd"
                        type="date"
                        placeholder="选择日期"
                        style="width: 100%;">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间：" prop="pickerDateE">
                    <el-date-picker
                        v-model="stayForm.pickerDateE"
                        value-format="yyyy-MM-dd"
                        type="date"
                        placeholder="选择日期"
                        style="width: 100%;">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="账号：" prop="number">
                    <el-autocomplete
                        v-model="stayForm.number"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入账号"
                        @blur="changeNumber"
                        @select="selectNumber">
                    </el-autocomplete>
                </el-form-item>
                <el-form-item label="真实姓名：">
                    <el-input v-model="stayForm.realyName" disabled></el-input>
                </el-form-item>
                <el-form-item label="班级：">
                    <el-input v-model="stayForm.class" disabled></el-input>
                </el-form-item>
                <el-form-item label="留校寝室：" prop="room">
                    <el-cascader
                        placeholder="请选择寝室"
                        :options="roomList"
                        @change="changeRoomItem"
                        style="width: 100%"
                        :title="getTitle(stayForm.room)"
                        v-model="stayForm.room">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="宿管老师：">
                    <el-input v-model="stayForm.teacher" disabled></el-input>
                </el-form-item>
                <el-form-item label="备注：">
                    <el-input
                        type="textarea"
                        placeholder="请输入留校说明"
                        :rows="3"
                        v-model="stayForm.remark"
                        maxlength="30"
                        show-word-limit>
                    </el-input>
                </el-form-item>
            </el-form>
			<div slot="footer" class="dialog-footer">
			    <el-button @click="cancelForm">取消</el-button>
			    <el-button type="primary" @click="submitStaySchool('stayForm')">确定</el-button>			    
			</div>
		</el-dialog>
    </div>
</template>

<script>
import XLSX from 'xlsx';
import FileSaver from 'file-saver';
import {str2Buffer} from './../../../tools/tool';

export default {
    data() {
        return {
            stayVisible: false, // 是否弹窗
            rowLen: 0, // 删除数据的长度
            totalNumber: 0, // 列表总数
            bed_number: null, // 床位号
            roomId: null, // 宿舍id
            stayTitle: '添加留校', // 留校标题
            selected: [], // 表格选中数组
            dormData: [], // 宿舍楼列表
            gradeList: [], // 班级列表
            roomList: [], // 宿舍楼/楼层/宿舍/床位列表
            listData: [], // 留校记录列表
            userList: [], // 用户列表
            loading: { // loading 状态
                status: false,
                txt: '获取数据...'
            },
            listParam: { // 留校记录列表搜索条件
                keyword: '', // 关键字搜索
                dormId: '', // 宿舍楼 id
                classId: [], // 班级 id
                pickerTime: [], // 开始时间和结束时间
                pageIndex: 1, // 分页当前页数
                pageSize: 10 // 每页数据数量
            },
            stayForm: { // 留校表单
                id: null,
                pickerDateS: '',
                pickerDateE: '',
                number: '',
                userId: '',
                realyName: '',
                class: '',
                room: [],
                teacher: '',
                remark: ''
            },
            rules: { // 表单验证
                pickerDateS: [
                    { required: true, validator: this.validatorStart, trigger: 'change' }
                ],
                pickerDateE: [
                    { required: true, validator: this.validatorEnd, trigger: 'change' }
                ],
                number: [
                    { required: true, message: '请输入账号', trigger: 'blur' }
                ],
                room: [
                    { required: true, message: '请选择留校寝室', trigger: 'change' }
                ]
            }
        }
    },
    created() {
        this.getList();
        this.getAllClass();
        this.getBuilding();
        this.getRoom();
    },
    computed: {
        /**
         * 获取寝室名称
         * @param {Array} val 数组
         */
        getTitle() {
            return (val) => {
                if (val.length === 4) {
                    let name = undefined;
                    this.roomList.forEach(item1 => {
                        if (item1.value == val[0]) {
                            item1.children.forEach(item2 => {
                                if (item2.value == val[1]) {
                                    item2.children.forEach(item3 => {
                                        if (item3.value == val[2]) {
                                            item3.children.forEach(item4 => {
                                                if (item4.value == val[3]) {
                                                    name = item1.label + ' / ' + item2.label + ' / ' + item3.label + ' / ' + item4.label;
                                                }
                                            })
                                        }
                                    })
                                }
                            })
                        }
                    })

                    return name;
                } else {
                    return undefined;
                }
            }
        },
    },
    methods: {
        /**
         * 获取宿舍列表
         */
        getBuilding() {
            const success = (res => {
                this.dormData = res.data;
            })

            this.$ajax.get('api/dormitory/dormitoryBuilding', {func: {success: success}})
        },
        /**
         * 动态改变标签的名字
         * @param {Array} val 选中值的 id
         */
        changeAddItem(val) {
            // this.listParam.classId = [];
            if (val.length !== 3) {
                this.$message.warning('该年级无绑定班级');
            }
        },
        /**
         * 动态改变标签的名字
         * @param {Array} val 选中值的 id
         */
        changeRoomItem(val) {
            if (val.length < 4) {
                this.stayForm.room = [];
                return false;
            }

            !is_empty(this.dormData) && this.dormData.forEach(item => {
                if (item.id == val[0]) {
                    this.stayForm.teacher = item.housemaster_name;
                }
            })

            this.roomId = val[2];
            this.bed_number = val[3];
        },
        /**
         * 获取寝室集合
         * 北苑1栋/4F/402/床位1 
         */
        getRoom() {
            const success = (res => {
                let tempArr = [];
                let tempData = res.data;

                tempData.forEach((item1, inx1) => {
                    let data1 = item1.children;

                    if (!is_empty(data1)) {
                        tempArr.push({
                            value: item1.id,
                            label: item1.name,
                            children: []
                        })

                        data1.forEach((item2, inx2) => {
                            let data2 = item2.children;

                            if (!is_empty(data2)) {
                                tempArr[inx1].children.push({
                                    value: item2.id,
                                    label: item2.name,
                                    children: []
                                })

                                data2.forEach((item3, inx3) => {
                                    let data3 = item3.children;

                                    if (!is_empty(data3)) {
                                        tempArr[inx1].children[inx2].children.push({
                                            value: item3.id,
                                            label: item3.number,
                                            children: []
                                        })

                                        data3.forEach(item4 => {
                                            tempArr[inx1].children[inx2].children[inx3].children.push({
                                                value: item4.bed_number,
                                                label: item4.bed_name
                                            })
                                        })
                                    } else {
                                        tempArr[inx1].children[inx2].children.push({
                                            value: item3.id,
                                            label: item3.number,
                                        })
                                    }
                                })
                            } else {
                                tempArr[inx1].children.push({
                                    value: item2.id,
                                    label: item2.name,
                                })
                            }
                        })
                    } else {
                        tempArr.push({
                            value: item1.id,
                            label: item1.name,
                        })
                    }
                })

                this.roomList = tempArr;
            })
            this.$ajax.get('api/dormitory/getDormitoryOrg', {params: {}, func: {success: success}}); 
        },
        /**
         * 从组织架构中获取班级
         */
        getAllClass(){
            let success = (res1 => {
                let tempArr = [];
                let tempData = res1.data ? res1.data[0].children : [];

                if (!is_empty(tempData)) {
                    tempData.forEach((val, index) => {
                        let data2 = val.children;

                        if (!is_empty(data2)) {
                            tempArr.push({
                                value: val.id,
                                label: val.name,
                                children: []
                            })

                            data2.forEach((res, index2) => {
                                let data3 = res.children;
                                
                                if (!is_empty(data3)) {
                                    tempArr[index].children.push({
                                        value: res.id,
                                        label: res.name,
                                        children: []
                                    })

                                    data3.forEach((tex, index3) => {
                                        tempArr[index].children[index2].children.push({
                                            value: tex.id,
                                            label: tex.name,
                                        })
                                    })
                                } else {
                                    tempArr[index].children.push({
                                        value: res.id,
                                        label: res.name,
                                    })
                                }
                            })
                        } else {
                            tempArr.push({
                                value: val.id,
                                label: val.name,
                            })
                        }
                    })
                }

                this.gradeList = tempArr;
            });
            let orgParam = {
                status: [1, 2],
                data_type: 'manage_tree'
            }

            this.$ajax.get('api/org/org', {params: orgParam, func: {success: success}})
        },
        /**
         * 获取留校记录列表
         */
        getList() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.listData = res.data.data;
                this.totalNumber = res.data.data_sum;
            })
            let params = {
                start_time: this.listParam.pickerTime[0],
                end_time: this.listParam.pickerTime[1],
                building_id: this.listParam.dormId,
                class_id: this.listParam.classId[this.listParam.classId.length - 1],
                keyword: this.listParam.keyword,
                page_index: this.listParam.pageIndex,
                page_size: this.listParam.pageSize,
            }

            this.$ajax.get('api/dormitory/detention',{params: params, func:{success: success}})
        },
        /**
         * 搜索列表
         */
        searchFunc() {
            this.listParam.pageIndex = 1;
            this.getList();
        },
        /**
         * 重置留校记录列表
         */
        resetList() {
            this.listParam = {
                keyword: '', 
                dormId: '', 
                classId: [],
                pickerTime: [],
                pageIndex: 1, 
                pageSize: 10 
            }

            this.getList();
        },
        /**
         * 选中学生数据
         * @param {Object} item 选中的信息
         */
        selectNumber(item) {
            this.stayForm.userId = item.id;
            this.stayForm.class = item.class;
            this.stayForm.realyName = item.name;

            if (item.dormitory.length === 4) {
                this.stayForm.room = item.dormitory;
                this.roomId = item.dormitory[2];
                this.bed_number = item.dormitory[3];
            } else {
                this.stayForm.room = [];
            }
        },
        changeNumber() {
            if (is_empty(this.userList)) {
                // this.stayForm.number = '';
                this.$message.warning('无法添加该账号')
            }
        },
        /**
         * 根据关键字查询数据
         */
        querySearchAsync(queryString, cb) {
            if (this.stayForm.number !== '') {
                this.stayForm.userId = '';
                this.stayForm.class = '';
                this.stayForm.realyName = '';

                let _this = this;
                let params = {
                    keyword: this.stayForm.number,
                    data_style: 2,
                    // page_index: 1,
                    // page_size: 10
                }
                let success = (res => {
                    let tempList = [];
                    this.userList = res.data;

                    this.userList.forEach(item => {
                        tempList.push({
                            value: item.user_number, 
                            id: item.user_id,
                            name: item.user_name,
                            class: is_empty(item.class) ? '' : item.class[0].rename,
                            dormitory: !is_empty(item.dormitory) ? [item.dormitory.building_id, item.dormitory.floor_id, item.dormitory.dormitory_id, item.dormitory.bed_number] : []
                        })
                    })

                    cb(tempList);
                });

                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    _this.$ajax.get('api/dormitory/getUserByKeyword', {params: params, func: {success: success}});
                }, 500);
            }
        },
        /**
         * 当前记录编辑
         * @param {Number} val 记录 id
         */
        newStaySchool(val) {
            this.stayVisible = true;
            
            if (val === 'add') {
                this.stayTitle = '添加留校';
                this.stayForm = {
                    id: null,
                    pickerDateS: '',
                    pickerDateE: '',
                    number: '',
                    realyName: '',
                    class: '',
                    userId: '',
                    room: [],
                    teacher: '',
                    remark: ''
                }
            } else {
                this.stayTitle = '编辑留校';
                this.stayForm.id = val.id;
                this.stayForm.pickerDateS = val.start_time;
                this.stayForm.pickerDateE = val.end_time;
                this.stayForm.number = val.user_number;
                this.stayForm.realyName = val.user_name;
                this.stayForm.class = is_empty(val.org_name) ? '' : val.org_name;
                this.stayForm.room = [val.building_id, val.floor_id, val.dormitory_id, val.bed_number];
                this.stayForm.teacher = val.housemaster_name;
                this.stayForm.remark = val.content;
                this.stayForm.userId = val.user_id;
                this.roomId = val.dormitory_id;
                this.bed_number = val.bed_number;
            }
            
            this.$nextTick(() => {
                this.$refs.stayForm.clearValidate();
            })
        },
        /**
         * 保存留校记录
         */
        submitStaySchool(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let params = {
                        id: this.stayForm.id,
                        dormitory_id: this.roomId,
                        bed_number: this.bed_number,
                        user_id: this.stayForm.userId,
                        start_time: this.stayForm.pickerDateS,
                        end_time: this.stayForm.pickerDateE,
                        content: this.stayForm.remark
                    }

                    const success = (res => {
                        this.stayVisible = false;

                        this.getList();
                    })

                    if (this.stayForm.id) {
                        this.$ajax.put("api/dormitory/detention", params, {func: {success: success}});
                    } else {
                        this.$ajax.post("api/dormitory/detention", params, {func: {success: success}});
                    }
                } else {
                    return false;
                }
            });
        },
        /**
         * 取消弹出
         */
        cancelForm() {
            this.stayVisible = false;
        },
        /**
         * 验证开始时间规则
         */
        validatorStart(rule, value, callback) {
            if (value === '') {
                callback(new Error('请选择开始时间'));
            } else {
                if (this.stayForm.pickerDateE && this.stayForm.pickerDateS > this.stayForm.pickerDateE) {
                    callback(new Error('开始时间不能大于结束时间'));
                } else {
                    callback();
                }
            }
        },
        /**
         * 验证结束时间规则
         */
        validatorEnd(rule, value, callback) {
            if (value === '') {
                callback(new Error('请选择结束时间'));
            } else {
                if (this.stayForm.pickerDateS && this.stayForm.pickerDateS > this.stayForm.pickerDateE) {
                    callback(new Error('结束时间不能小于开始时间'));
                } else {
                    callback();
                }
            }
        },
        /**
         * 确认批量删除留校记录
         */
        deleteAllConfirm() {
            if(this.selected.length === 0) {
                this.$message.warning("请选择要删除的项");
                return false;
            }

            let yes = (res => {
                let ids = [];
                this.rowLen = this.selected.length;

                this.selected.forEach(item => {
                    ids.push(item.id);
                })

                this.deleteList(ids);
            })
            let cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt: '确定要删除这些项吗？'});
        },
        /**
         * 确认是否删除留校记录
         * @param {Number} id 留校记录 id
         */
        deleteConfirm(id) {
            const yes = (res => {
                this.rowLen = 1;
                this.deleteList(id);
            })
            const cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt: '确定要清空该记录吗？'});
        },
        /**
         * 删除留校记录
         * @param {Number/Array} id 留校记录 id
         */
        deleteList(id) {
            this.loading.status = true;

            let success = (res => {
                this.$message.success(res.msg);
                
                if (this.listData.length - this.rowLen === 0) {
                    if (this.listParam.pageIndex > 1) {
                        this.listParam.pageIndex-- ;
                    } else {
                        this.listParam.pageIndex = 1;
                    }
                }

                this.getList();
            });
            let fail = (res =>{
                this.$message.error(res.msg);

                this.getList();
            }) 
            let params = {
                id
            }

            this.$ajax.delete('api/dormitory/detention', {params: params, func: {success: success, fail: fail}});
        },
        /**
         * 获取全部数据后导出
         */
        async getAllData() {
            if (this.totalNumber <= this.listParam.pageSize) {
                this.exportExcel(this.listData);
            } else {
                let All = [];
                let len = Math.ceil(this.totalNumber / 100);
                let success = (res=>{
                    All = [...All, ...res.data.data];
                })

                for (let i=1; i<=len; i++) {
                    let params = {
                        page_index: i,
                        page_size: 100,
                    }

                    await this.$ajax.get('api/dormitory/detention',{params: params, func:{success: success}});
                }

                this.exportExcel(All);
            }
        },
        /**
         * 导出Excel表
         * @param {Array} allData 全部数据
         */
        exportExcel(allData) {       
            if(allData.length === 0){
                this.$message.warning("导出的数据为空！");
                return false;
            }
            
            let exportList = [];
            const defaultCellStyle =  { font: { name: "Verdana", sz: 14, color: "FF00FF88"}, fill: {fgColor: {rgb: "FFFFAA00"}}};
            const wopts = { bookType:'xlsx', bookSST:false, type:'binary', defaultCellStyle: defaultCellStyle, showGridLines: false};
            const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };

            for (let i = 0; i <= allData.length - 1;  i++) {
                if(i===0){
                    this.live_name  =  allData[i].l_name
                }

                exportList.push({
                    "开始时间": allData[i].start_time,
                    "结束时间": allData[i].end_time,
                    "账号": allData[i].user_number,
                    "真实姓名": allData[i].user_name,
                    "班级": allData[i].org_name,
                    "留校宿舍楼": allData[i].building_name,
                    "留校寝室": allData[i].dormitory_name,
                    "床位": allData[i].bed_number,
                    "宿管老师": allData[i].housemaster_name,
                    "联系电话": allData[i].housemaster_telphone,
                    "留校说明": allData[i].content
                });
            }

            wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(exportList)
            wb.Sheets['Sheet1']["!cols"] = [{
                wpx: 140
            }, {
                wpx: 140
            }, {
                wpx: 140
            }, {
                wpx: 130
            }, {
                wpx: 120
            }, {
                wpx: 120
            }, {
                wpx: 100
            }, {
                wpx: 80
            }, {
                wpx: 120
            }, {
                wpx: 140
            }, {
                wpx: 350
            }];

            //创建二进制对象写入转换好的字节流
            let tmpDown =  new Blob([str2Buffer(XLSX.write(wb, wopts))], { type: "application/octet-stream" });
            FileSaver.saveAs(tmpDown, `留校记录.xlsx`);
        },
        /**
         * 跳到批量导入页面
         */
        batchImport(){
            this.$router.push("/life/dormitory/school-batch-import")
        },
        /**
         * 表格序号
         * @param {Number} index  序号
         */
        tableIndex(index) {
            return index + (this.listParam.pageIndex - 1) * this.listParam.pageSize + 1;
        },
        /**
         * 列表数据多选
         * @param {Array} val 选中数据的数组
         */
        tableSelectionChange(val) {
            this.selected = val;
        },
        /**
         * 设置列表每页数据数量
         */
        setCurrentSize(val) {
            this.listParam.pageIndex = 1;
            this.listParam.pageSize = val;

            this.getList();
        },
        /**
         * 设置列表的当前页数
         * @param {Number} val 页数
         */
        setCurrentPage(val) {
            this.listParam.pageIndex = val;

            this.getList();
        },
    },
}
</script>

<style lang="scss">
    .stay-school-record {
        .open-width {
			.el-date-editor {
				width: 100%;
				vertical-align: middle;
			}
		}

        .stay-form {
            .el-autocomplete {
                width: 100%;
            }
        }
    }
</style>